package uds.android.fitdroid.control;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import uds.android.fitdroid.db.*;

import java.util.List;

//TRAINING data = insert/select
//TRIAL records = insert only
//OVERALL records = insert/update/select

//Owner - Himangshu

public class DbControl extends Activity {
   
   private static final int MENU_MANAGE = 0;
   
   DataHelper datahelper;
   DataHelperBLOB datahelperblob;
   TrialRecordsHelper trialrecords;
   GPSHelper gpshelper;
   


private Long ex_id;
   private String ex_name;
   private Long trials;
   private Long time;
   private String location;
   private String date;
   private byte[] data;
   private boolean toBeResumed;
   private TextView output;

   public boolean isToBeResumed() {
	return toBeResumed;
}

public void setToBeResumed(boolean toBeResumed) {
	this.toBeResumed = toBeResumed;
}

public Long getEx_id() {
	   return ex_id;
   }

   public void setEx_id(Long ex_id) {
	   this.ex_id = ex_id;
   }

   public String getEx_name() {
	   return ex_name;
   }

   public void setEx_name(String ex_name) {
	   this.ex_name = ex_name;
   }

   public Long getTrials() {
	   return trials;
   }

   public void setTrials(Long trials) {
	   this.trials = trials;
   }

   public Long getTime() {
	   return time;
   }

   public void setTime(Long time) {
	   this.time = time;
   }

   public String getLocation() {
	   return location;
   }

   public void setLocation(String location) {
	   this.location = location;
   }

   public String getDate() {
	   return date;
   }

   public void setDate(String date) {
	   this.date = date;
   }

   public byte[] getData() {
	   return data;
   }

   public void setData(byte[] data) {
	   this.data = data;
   }

   public DataHelper getDatahelper() {
	return datahelper;
}

public DataHelperBLOB getDatahelperblob() {
	return datahelperblob;
}

public TrialRecordsHelper getTrialrecords() {
	return trialrecords;
}

public GPSHelper getGpshelper() {
	return gpshelper;
}

public void setGpshelper(GPSHelper gpshelper) {
	this.gpshelper = gpshelper;
}

public void insertGPSData(Long id, byte[] data, String date, Boolean toBeResumed){
	String oldData = null;
	String oldDate = null;
	if(toBeResumed == true){
		new SelectGPSDataTask().execute(id.toString(), oldData, "true", oldDate);
		//TODO - for Luc
		//you get old data here, combine 'oldData' and 'data' in whatever way you want and store in 'data'
	}
	new InsertGPSDataTask().execute(id.toString(), data.toString(), date, "false");
}

//TODO
//for LUC
//I don't know why you want this
/*
public WhateverTypeYouWant readGPSData(Long id){
	String gpsDataString = new String();
	String date;
	new SelectGPSDataTask().execute(id.toString(), gpsDataString, "false", date );
	//populate your data structure and return
}
*/
public void insertTrainingData(Long id, byte[] data){
	   new InsertTrainingDataTask().execute(id.toString(),
       		data.toString());
   }

public byte[] readTrainingData(Long id){
	String dataString = new String();
	new SelectTrainingDataTask().execute(id.toString(), dataString);
	return dataString.getBytes();
}

//please enter date formatted as 2010-05-28 16:20:55
//YYYY-MM-DD HH:MM:SS
public void insertNewTrial(Long id, Long numTrials, Long time, String date, String location ){
	new InsertDataTask().execute(id.toString(), location, numTrials.toString(), time.toString(), date);
}

//What do you want? Will code accordingly
public void readStats(Long id){
	new SelectDataTask().execute(id.toString());
}
   
   @Override
   public void onCreate(final Bundle savedInstanceState) {
	   
	   
      super.onCreate(savedInstanceState);
      this.datahelper = new DataHelper(this);
      this.datahelperblob = new DataHelperBLOB(this);
      this.trialrecords = new TrialRecordsHelper(this);
      this.gpshelper = new GPSHelper(this);
   }

   
   @Override
   public boolean onCreateOptionsMenu(final Menu menu) {
      menu.add(0, DbControl.MENU_MANAGE, 1, "Manage Database").setIcon(android.R.drawable.ic_menu_manage);
      return super.onCreateOptionsMenu(menu);
   }

   @Override
   public boolean onOptionsItemSelected(final MenuItem item) {
      switch (item.getItemId()) {      
      case MENU_MANAGE:
          this.startActivity(new Intent(DbControl.this, ManageData.class));          
          return true;
      default:
         return super.onOptionsItemSelected(item);
      }
   }

   private class InsertTrainingDataTask extends AsyncTask<String, Void, Void> {
      private final ProgressDialog dialog = new ProgressDialog(DbControl.this);

      // can use UI thread here
      protected void onPreExecute() {
         this.dialog.setMessage("Inserting data...");
         this.dialog.show();
      }

      // automatically done on worker thread (separate from UI thread)
      protected Void doInBackground(String... args) {
         DbControl.this.getDatahelperblob().insertBLOB(args[0], args[1]);
         return null;
      }

      // can use UI thread here
      protected void onPostExecute(final Void unused) {
         if (this.dialog.isShowing()) {
            this.dialog.dismiss();
         }
         // reset the output view by retrieving the new data
         // (note, this is a naive example, in the real world it might make sense
         // to have a cache of the data and just append to what is already there, or such
         // in order to cut down on expensive database operations)
         //new SelectDataTask().execute("1");
      }
   }

   private class InsertDataTask extends AsyncTask<String, Void, Void> {
	      private final ProgressDialog dialog = new ProgressDialog(DbControl.this);

	      // can use UI thread here
	      protected void onPreExecute() {
	         this.dialog.setMessage("Inserting data...");
	         this.dialog.show();
	      }

	      // automatically done on worker thread (separate from UI thread)
	      protected Void doInBackground(final String... args) {
	    	 //Log.e("NOTE", "ARGS :" + args[0] + " " + args[1] + " " + args[2]); 
	    	 DbControl.this.getTrialrecords().insertTrial(args[0].trim(), args[1].trim(),args[2].trim(),args[3].trim(),args[4].trim()); 
	         DbControl.this.getDatahelper().insert(args[0].trim(), args[2].trim(), args[3].trim());
	         return null;
	      }

	      // can use UI thread here
	      protected void onPostExecute(final Void unused) {
	         if (this.dialog.isShowing()) {
	            this.dialog.dismiss();
	         }
	         // reset the output view by retrieving the new data
	         // (note, this is a naive example, in the real world it might make sense
	         // to have a cache of the data and just append to what is already there, or such
	         // in order to cut down on expensive database operations)
	         //new SelectDataTask().execute("1");
	      }
	   }

   
   private class InsertGPSDataTask extends AsyncTask<String, Void, Void> {
	      private final ProgressDialog dialog = new ProgressDialog(DbControl.this);

	      // can use UI thread here
	      protected void onPreExecute() {
	         this.dialog.setMessage("Inserting data...");
	         this.dialog.show();
	      }

	      // automatically done on worker thread (separate from UI thread)
	      protected Void doInBackground(final String... args) {
	    	 //Log.e("NOTE", "ARGS :" + args[0] + " " + args[1] + " " + args[2]); 
	    	 DbControl.this.getGpshelper().insertGPS(args[0].trim(), args[1].trim(),args[2].trim(),args[3].trim()); 
	         return null;
	      }

	      // can use UI thread here
	      protected void onPostExecute(final Void unused) {
	         if (this.dialog.isShowing()) {
	            this.dialog.dismiss();
	         }
	         // reset the output view by retrieving the new data
	         // (note, this is a naive example, in the real world it might make sense
	         // to have a cache of the data and just append to what is already there, or such
	         // in order to cut down on expensive database operations)
	         //new SelectDataTask().execute("1");
	      }
	   }

   
   private class SelectDataTask extends AsyncTask<String, Void, String> {
      private final ProgressDialog dialog = new ProgressDialog(DbControl.this);

      // can use UI thread here
      protected void onPreExecute() {
         this.dialog.setMessage("Selecting data...");
         this.dialog.show();
      }

      // automatically done on worker thread (separate from UI thread)
      protected String doInBackground(final String... args) {
    	  //System.out.println("here..");
         List<String[]> names = DbControl.this.getDatahelper().selectAll(Long.parseLong(args[0]));
    	  StringBuilder sb = new StringBuilder();
         for (String[] name : names) {
            sb.append("Average trials/min : " + name[2] + 
            		"\nLast trial : " + name[3] + "\n");
         }
         //System.out.println("...exiting");
         return sb.toString();
      }

      // can use UI thread here
      protected void onPostExecute(final String result) {
         if (this.dialog.isShowing()) {
            this.dialog.dismiss();
         }
         DbControl.this.output.setText(result);
      }
   }

   private class SelectTrainingDataTask extends AsyncTask<String, Void, Void> {
	      private final ProgressDialog dialog = new ProgressDialog(DbControl.this);

	      // can use UI thread here
	      protected void onPreExecute() {
	         this.dialog.setMessage("Selecting data...");
	         this.dialog.show();
	      }

	      // automatically done on worker thread (separate from UI thread)
	      protected Void doInBackground(final String... args) {
	    	  //System.out.println("here..");
	         args[1] = DbControl.this.getDatahelperblob().getData(Long.parseLong(args[0])).toString();
			return null;
	
	      }

	      // can use UI thread here
	      protected void onPostExecute(final String result) {
	         if (this.dialog.isShowing()) {
	            this.dialog.dismiss();
	         }
	         DbControl.this.output.setText(result);
	      }
	   }
   
   private class SelectGPSDataTask extends AsyncTask<String, Void, Void> {
	      private final ProgressDialog dialog = new ProgressDialog(DbControl.this);

	      // can use UI thread here
	      protected void onPreExecute() {
	         this.dialog.setMessage("Selecting data...");
	         this.dialog.show();
	      }

	      // automatically done on worker thread (separate from UI thread)
	      protected Void doInBackground(final String... args) {
	    	  //System.out.println("here..");
	         args[1] = DbControl.this.getGpshelper().getData(Long.parseLong(args[0]), Boolean.parseBoolean(args[2]), args[3]).toString();
			return null;
	
	      }

	      // can use UI thread here
	      protected void onPostExecute(final String result) {
	         if (this.dialog.isShowing()) {
	            this.dialog.dismiss();
	         }
	         DbControl.this.output.setText(result);
	      }
	   }
   
   /*
   private class DeleteDataTask extends AsyncTask<String, Void, Void> {
      private final ProgressDialog dialog = new ProgressDialog(DbControl.this);

      // can use UI thread here
      protected void onPreExecute() {
         this.dialog.setMessage("Deleting data...");
         this.dialog.show();
      }

      // automatically done on worker thread (separate from UI thread)
      protected Void doInBackground(final String... args) {
         DbControl.this.getDatahelper().deleteAll();
         return null;
      }

      // can use UI thread here
      protected void onPostExecute(final Void unused) {
         if (this.dialog.isShowing()) {
            this.dialog.dismiss();
         }
         // reset the output view by retrieving the new data
         // (note, this is a naive example, in the real world it might make sense
         // to have a cache of the data and just append to what is already there, or such
         // in order to cut down on expensive database operations)
         new SelectDataTask().execute();
      }
   }*/
}